#! /usr/bin/env python
#coding=utf-8
from uliweb import expose
from sqlalchemy import *
from uliweb.orm import *
from uliweb.utils.pyini import Ini
from sqlalchemy.sql import select
from sqlalchemy.sql import and_, or_, not_
import time, sys
sys.path.insert(0, '../apps')

from departments.models import *
from myuser.models import *

from systems.models import *
from requirements.models import *
from assignments.models import *

from charts.models import *
from tasks.models import *

import datetime
from datetime import date
from get_month_quarter import *

db = get_db_connection()

def run():
    
    #从settings.ini获取任务类型编号
    #settings = Ini('../apps/settings.ini')
    req_task = get_model('tasks_develop')
    req_milestone = get_model('tasks_milestone')
    req_plan = get_model('milestone_plan')
    req_ass = get_model('assignment')
#    req_t_detail = get_model('tasks_develop_report_detail')
    #获取本周末日期

    today = datetime.date.today()
#    today = month_last_day
    sql = select([req_milestone.c.id,req_milestone.c.finish_date,
                  req_milestone.c.status,req_plan.c.plan_date],
                  and_(req_plan.c.id == req_milestone.c.milestone_plan))

    rs_sql = sql.execute()
    
    for row in rs_sql:
        milestone_id,finish_date,status,plan_date = row
#        print 'plan_date',plan_date
        if not plan_date:
            continue
        if not finish_date:
            if plan_date < today and status != '2':
                req_milestone.table.update(req_milestone.c.id ==milestone_id).execute(status = '2')
        else:
            if plan_date < finish_date and status != '2':
                req_milestone.table.update(req_milestone.c.id ==milestone_id).execute(status = '2')            
            if plan_date > finish_date and status != '3':
                req_milestone.table.update(req_milestone.c.id ==milestone_id).execute(status = '3')
    #---处理任务延迟情况----#
    obj_task =  req_task.filter(or_(and_(req_task.c.stage != 'FN',
                                         req_task.c.stage != '00'),
                                    and_(req_task.c.stage == '00',
                                         req_task.c.begin_time <= today),
#                                    and_(req_task.c.modified_date >= today,
                                    and_(req_task.c.status != '1',
                                         req_task.c.stage == 'FN'))) 
    for row in obj_task:
        task = row.id
        
        if row.version_headerId != None:
            task_head = row._version_headerId_
        else:
            task_head = row.id
        dev_task = row.task_id    
        delay_stat = ''
     
        delay = select([req_plan.c.id,
                        req_plan.c.name,req_plan.c.plan_date],
                        and_(req_plan.c.task == task_head,
                            req_plan.c.plan_date < today
                            ))
        
        #      now = datetime.datetime.now()
        #      print 'two for begin',now
        
        delay_rs = delay.execute()
        for row_d in delay_rs:
        #          dev_task,devid,planid,plan_name,plan_date = row_d
            planid,plan_name,plan_date = row_d
            delay_milestone = select([func.max(req_milestone.c.finish_date)],
                                    and_(req_milestone.c.task == task,
                                        req_milestone.c.milestone_plan == planid))
            delay_milestone_rs = delay_milestone.execute()
            
            #初始化finish_date
            finish_date = None
            
            for row_m in delay_milestone_rs:
                finish_date, = row_m
                #print 'finish_date',finish_date
                
            if not finish_date or finish_date>= today:
                if finish_date and plan_date >=today and finish_date <= plan_date:
                    continue
                else:
        #                  delay_stat = 'delay'
        #                  break
                    if finish_date != None:
                        delay_stat = delay_stat+str(dev_task)+'-'+plan_name+'('+u'计划完成时间:'+str(plan_date)[0:10]+'|'+u'实际完成时间:'+str(finish_date)[0:10]+')'+';\n'
                    else:
                        delay_stat = delay_stat+str(dev_task)+'-'+plan_name+'('+u'计划完成时间:'+str(plan_date)[0:10]+'|'+u'实际完成时间:'+u'未填写'+')'+';\n'
                    #print 'delay_stat'#,delay_stat
        
        #          now = datetime.datetime.now()
        #          print 'two for end',now
        #data[y]['delay_milestone'] = delay_stat
                
        if (delay_stat or (row.end_time < today and row.status != '3' and row.stage != 'FN')) and (row.status != '4' or row.status != '5' ):
            req_task.table.update(req_task.c.id ==task).execute(status = '2')
#            if row.status != '2':
#                req_ass.table.update(req_ass.c.id ==row.assignment.id).execute(status = '2')
        elif row.status == '2':
            req_task.table.update(req_task.c.id ==task).execute(status = '1')
        


if __name__ == '__main__':
    try:
        db.begin()
        run()
        db.commit()
        log.info("finish")
    except Exception, e:
        db.rollback()
        log.exception(e)
        log.error('error')
        raise
